﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;

namespace Excell_On_Services.Models
{
    public class Cart
    {
        private List<CartLine> lines = new List<CartLine>();
        public IList<CartLine> Lines { get { return lines.AsReadOnly(); } }

        public void AddItem(Service service, int quantity, DateTime startDate, DateTime endDate)
        {
            var line = lines.FirstOrDefault(x => x.Service.ServiceID == service.ServiceID);
            if (line == null)
                lines.Add(new CartLine { Service = service, Quantity = quantity, StartDate = startDate, EndDate = endDate  });
            else
                line.Quantity += quantity;
            if (line.Quantity < 0)
                RemoveLine(service);
        }

        public decimal ComputeTotalValue()
        {
            return lines.Sum(l => l.Service.Price * l.Quantity * (long)((TimeSpan)(l.EndDate - l.StartDate)).TotalDays);
        }

        public void Clear()
        {
            lines.Clear();
        }

        public void RemoveLine(Service service)
        {
            lines.RemoveAll(l => l.Service.ServiceID == service.ServiceID);
        }

        public void RemoveLine(int serviceID)
        {
            lines.RemoveAll(l => l.Service.ServiceID == serviceID);
        }

        public void UpdateItem(int serviceID, int quantity, DateTime startDate, DateTime endDate)
        {
            var line = lines.FirstOrDefault(x => x.Service.ServiceID == serviceID);
            if (line != null)
            {
                line.Quantity = quantity;
                line.StartDate = startDate;
                line.EndDate = endDate;
                if (line.Quantity <= 0)
                {
                    RemoveLine(serviceID);
                }
            }
        }
    }

    public class CartLine
    {
        public Service Service { get; set; }
        
        [Required(ErrorMessage="Quantity is required")]

        public int Quantity { get; set; }


        public DateTime StartDate { get; set; }


        public DateTime EndDate { get; set; }
    }
}